import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    StyleSheet,
    SafeAreaView,
    Modal,
    ScrollView,
    DeviceEventEmitter,
    FlatList,
    ActivityIndicator,
    Dimensions,
    Animated
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Constant from '../../utils/Constant'//全局变量
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";

const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

const listbox = Math.floor((screenW - 40 - 20) / 3);

export default class RechargePop extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedIndex: -1,
            inputMoney: '',
            totalPay: 0,
            isAgree: true,
            dataSource: [],
            payData: {},
            modalAnimation: new Animated.Value(0),
            accountType: this.props.accountType ? this.props.accountType:1 //1：现金充值，2：保证金充值
        };
    }

    componentDidUpdate(prevProps) {
        if (this.props.visible && !prevProps.visible) {
            this.animateIn();
        } else if (!this.props.visible && prevProps.visible) {
            this.animateOut();
        }
    }

    componentDidMount() {
        if (this.props.visible) {
            this.animateIn();
        }
        this.getCommonGoodsProdList()
    }

    animateIn = () => {
        Animated.timing(this.state.modalAnimation, {
            toValue: 1,
            duration: 300,
            useNativeDriver: true,
        }).start();
    };

    animateOut = () => {
        Animated.timing(this.state.modalAnimation, {
            toValue: 0,
            duration: 300,
            useNativeDriver: true,
        }).start();
    };

    getCommonGoodsProdList() {
        this.Loading.show()
        HttpUtils.postRequest(HttpUrls.getCommonGoodsProdList, { goodsType: 1 })
            .then((result) => {
                this.Loading.hide()
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    this.setState({
                        dataSource: data.resultList
                    })
                }
            })
            .catch((error) => {
                this.Loading.hide()
            });
    }

    render() {
        const translateY = this.state.modalAnimation.interpolate({
            inputRange: [0, 1],
            outputRange: [screenH, 0],
        });
        return (
            <TouchableOpacity
                activeOpacity={1}
                style={styles.container}
                onPress={() => {
                    this.props.onClose()
                }}
            >
                <Animated.View
                    style={[
                        { backgroundColor: '#fff', flexDirection: 'column', width: '100%' },
                        { transform: [{ translateY }] }
                    ]}
                >
                    <View onStartShouldSetResponder={() => true}>
                        {this.renderRecharge()}
                        {this.renderAgreement()}
                        {this.renderBottomBtn()}
                    </View>
                </Animated.View>


                <Loading onRef={(ref) => (this.Loading = ref)} />

            </TouchableOpacity>
        );
    }

    pay() {
        if (this.state.totalPay <= 0) {
            return;
        }
        if (this.state.totalPay < 0.01) {
            ToastToUser('充值金额不能小于0.01元')
            return;
        }
        if (!this.state.isAgree) {
            ToastToUser('请先同意《帅车平台充值消费协议》')
            return;
        }

        let param = {
            merchantId: Constant.userInfo.merchantId,
            userId: Constant.userInfo.userId,
            totalAmount: this.state.totalPay * 100, //服务端以分为单位
            accountType: this.state.accountType
        }

        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.balanceRechargeSaveOrder, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    let payData = {
                        totalAmount: data.totalAmount,
                        orderId: data.orderId,
                        goodsName: data.goodsName,
                        goodsDesc: data.goodsDesc,
                        tradeType: data.tradeType,
                    }
                    this.paySubmit(payData)
                    // this.props.navigation.navigate('ConfirmPayPage', {payData: payData})
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    paySubmit(payData) {
        let param = {
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            totalAmount: payData.totalAmount,
            payChannel: 10,
            bizOrderId: payData.orderId, //------------业务订单id
            orderBody: payData.goodsName,
            orderSubject: payData.goodsDesc,
            tradeType: payData.tradeType
        }

        if (this.Loading) {
            this.Loading.show()
        }
        HttpUtils.postRequest(HttpUrls.paymentOrderGenerate, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    let channelResult = data.channelResult
                    if (channelResult) {
                        if (this.props.onClose) {
                            this.props.onClose()
                        }
                        this.props.navigation.navigate('WebView', {source: channelResult})
                    }
                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    renderRecharge() {
        return (
            <View style={styles.rechargeContain}>
                <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                    <View style={{ width: 2, height: 16, backgroundColor: '#FEDD35' }}></View>
                    <Text style={{ fontSize: 16, color: '#333333', marginLeft: 8, fontSize: 16, fontWeight: '500' }}>余额充值</Text>
                </View>

                <View style={styles.rechargeCheckContain}>
                    {
                        this.state.dataSource.map((item, index) => {
                            return (
                                <TouchableOpacity style={[this.state.selectedIndex == index ? styles.rechargeMoneyItemCheckContain : styles.rechargeMoneyItemContain, { marginLeft: index % 3 == 0 ? 0 : 10, marginTop: index / 3 == 0 ? 0 : 20 }]}
                                    activeOpacity={0.8}
                                    onPress={() => {
                                        this.setState({
                                            selectedIndex: index,
                                            inputMoney: '',
                                            totalPay: item.presentPriceYuan
                                        })
                                    }}>
                                    <Text style={styles.rechargeText}>￥<Text style={styles.rechargeText2}>{item.presentPriceYuan}</Text></Text>
                                    {this.state.selectedIndex == index ? <Image style={styles.checkImg} source={require('source/image/bottom_right_check.png')}></Image> : null}
                                </TouchableOpacity>
                            )
                        })
                    }
                    <View style={[this.state.selectedIndex == 10000 ? styles.rechargeMoneyItemCheckContain : styles.rechargeMoneyItemContain, { marginLeft: this.state.dataSource.length % 3 == 0 ? 0 : 10, marginTop: this.state.dataSource.length / 3 == 0 ? 0 : 20 }]}>
                        <TextInput style={styles.rechargeInput} placeholder='输入金额' placeholderTextColor={'#999999'} keyboardType='numeric'
                            value={this.state.inputMoney}
                            onFocus={() => {
                                this.setState({
                                    selectedIndex: 10000,
                                    totalPay: 0
                                })
                            }}
                            onChangeText={(changeText) => {
                                this.setState({
                                    totalPay: parseFloat(changeText),
                                    inputMoney: changeText
                                })
                            }}></TextInput>
                        {this.state.selectedIndex == 10000 ? <Image style={styles.checkImg} source={{ uri: 'bottom_right_check' }}></Image> : null}
                    </View>
                </View>

                <Text style={[styles.rechargeDesText, { marginTop: 20 }]}>余额说明</Text>
                <Text style={[styles.rechargeDesText, { marginTop: 10 }]}>账户余额用于查询维保出险记录、合同费用、检测系统使用等服务，充值前请详细阅读《帅车平台充值消费协议》，并勾选同意。</Text>
            </View>
        )
    }

    renderAgreement() {
        return (
            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 20, }}>
                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                    <TouchableOpacity
                        style={{ width: 20, height: 20, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}
                        onPress={() => {
                            this.setState({
                                isAgree: !this.state.isAgree
                            })
                        }}>
                        <Image style={styles.bottomCheckImg} source={this.state.isAgree ? require('source/image/icon_selector_checked.png') : require('source/image/icon_selector_unchecked.png')}></Image>
                    </TouchableOpacity>
                    <Text style={{ color: '#333333', fontSize: 12, marginLeft: 4, }}>我已阅读并同意</Text>
                    <TouchableOpacity
                        onPress={() => {
                            let url = Constant.webDomain + '/static/protocol/rechargeConsumption.html'
                            this.props.navigation.navigate('WebView', { source: url })
                        }}>
                        <Text style={{ color: '#ED542E', marginLeft: 2, fontSize: 12 }}>《帅车平台充值消费协议》</Text>
                    </TouchableOpacity>
                </View>

            </View>
        )
    }

    renderBottomBtn() {
        return (
            <View style={[styles.bottomBox, { height: 50 + Constant.bottomHeight }]}>
                <View style={styles.bottomBox1}>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={{ color: '#333333', fontSize: 12, marginTop: 5, }}>应付：</Text>
                        <Text style={{ color: '#ED542E', fontSize: 20, fontWeight: '500', marginLeft: 5 }}>{this.state.totalPay}</Text>
                        <Text style={{ color: '#ED542E', fontSize: 12, marginLeft: 2, marginTop: 5 }}>元</Text>
                    </View>

                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            this.pay()
                        }}
                        style={{ marginTop: 16, marginBottom: 16 }}
                    >
                        <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
                            colors={this.state.totalPay > 0 ? ['#FFEF3A', '#FFDB1B'] : ['#F5F5F5', '#F5F5F5']}
                            style={styles.rechargeBox}>
                            <Text style={styles.rechargeText}>确认订单</Text>

                        </LinearGradient>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        top: 0,
        backgroundColor: '#rgba(0,0,0,0.5)',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'flex-end'
    },
    rechargeContain: {
        width: '100%',
        paddingBottom: 20,
        padding: 20,

    },
    rechargeCheckContain: {
        flexWrap: 'wrap',
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    rechargeMoneyItemContain: {
        width: listbox,
        height: 46,
        borderWidth: 1,
        borderColor: '#E5E5E5',
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center',
    },
    rechargeMoneyItemCheckContain: {
        width: listbox,
        height: 46,
        borderWidth: 1,
        borderColor: '#FFDE00',
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    checkImg: {
        width: 20,
        height: 20,
        position: 'absolute',
        right: 0,
        bottom: 0
    },
    rechargeText: {
        fontSize: 14,
        color: '#999999'
    },
    rechargeText2: {
        fontSize: 20,
        fontWeight: '500',
        color: '#333333'
    },
    rechargeDesText: {
        fontSize: 12,
        color: '#999999',
        lineHeight: 17,
    },
    rechargeInput: {
        fontSize: 18,
        color: '#333333'
    },
    bottomCheckImg: {
        width: 18,
        height: 18,
        resizeMode: 'contain'
    },
    bottomBox: {
        backgroundColor: '#fff',
        width: '100%',
    },
    bottomBox1: {
        height: 50,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 16,
        borderTopColor: '#e4e4e4',
        borderTopWidth: 0.5
    },
    rechargeBox: {
        width: 143,
        height: 36,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 18,
    },
    rechargeText: {
        fontSize: 14,
        color: '#333333',
    },
})